package com.cavalier.surtr.amop.receiver;

import com.alibaba.fastjson.JSON;
import com.cavalier.surtr.amop.JavaMailUtils;
import com.cavalier.surtr.amop.provider.MessageSender;
import com.cavalier.surtr.entity.DTO.ucCenter.PermissionDTO;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by archangle on 17/3/6.
 */
@Component
@RabbitListener(queues = "test_queue")
public class UserListener {

    private static Logger logger = LoggerFactory.getLogger(MessageSender.class);

    @Autowired
    private JavaMailUtils javaMailUtils;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @RabbitHandler
    public void receive(@Payload String json, Message message, Channel channel) {
        logger.info("test_queue : 消费者接受参数为" + json);
        if (null != json) {
            PermissionDTO permissionDO = JSON.parseObject(json, PermissionDTO.class);
            if (null != permissionDO) {
                try {
                    // TODO: 相关业务，写在这里，业务成功，则手动ack，失败，则执行相应操作：对应下面三种情况:
                    /**
                     * 业务正常执行，手动ack，确认消息正常消费
                     * */
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                    redisTemplate.opsForValue().set(message.getMessageProperties().getDeliveryTag()+"_MQ",json,6000, TimeUnit.MILLISECONDS);
                    String jsonStr=redisTemplate.opsForValue().get(message.getMessageProperties().getDeliveryTag()+"_MQ");
                    logger.info(jsonStr);
                    /**
                     * 异常，业务执行异常时，手动ack，讲消息重新入队
                     *channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                     *
                     *
                     * 直接丢弃消息
                     * channel.basicReject(message.getMessageProperties().getDeliveryTag(), true); // 拒绝消息
                     * */
//                    javaMailUtils.sendMailSystemLogger(new Date().toString(), MQConstant.PLATFORM_NAME,MQConstant.DEV_DOMAIN,"www.baidu.com","消息成功消费");
                } catch (Exception e) {
                    logger.error("处理异常："+e.getMessage());
                }
            }
        }
    }



}
